var qiniu_page={};
/**
 *
 * @type {{}}
 */
qiniu_page.action={
    initBody:function () {
        qiniu_page.interface.init();
        qiniu_page.interface.uploadObjectInit();
        qiniu_page.action.bindEvent();
    },
    bindEvent:function () {
        $("#uploadButton").click(function () {
            qiniu_page.action.uploadFile();
            return false;
        });
        $("#file").change(function () {
            qiniu_page.action.uploadFile();
            return false;
        });
        $("#qiniuDeleteByKeyButton").click(function () {
            qiniu_page.action.qiniuDeleteByKey();
            return false;
        });
    },
    uploadFile:function () {
        var obj = $("#file");
        var fileName = obj.val();
        var suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length);
        var file = obj.get(0).files[0];	                                           //上传的文件
        var size = file.size > 1024 ? file.size / 1024 > 1024 ? file.size / (1024 * 1024) > 1024 ? (file.size / (1024 * 1024 * 1024)).toFixed(2) + 'GB' : (file.size
            / (1024 * 1024)).toFixed(2) + 'MB' : (file.size
            / 1024).toFixed(2) + 'KB' : (file.size).toFixed(2) + 'B';

        var params = {
            suffix :suffix
        };
        var onSuccess = function (resultData) {
            if(resultData.success == 1){
                var observer = {                         //设置上传过程的监听函数
                    next(resultData){                        //上传中(result参数带有total字段的 object，包含loaded、total、percent三个属性)
                        Math.floor(resultData.total.percent);//查看进度[loaded:已上传大小(字节);total:本次上传总大小;percent:当前上传进度(0-100)]
                    },
                    error(err){                          //失败后
                        alert(err.message);
                    },
                    complete(res){                       //成功后
                        // ?imageView2/2/h/100：展示缩略图，不加显示原图
                        // ?vframe/jpg/offset/0/w/480/h/360：用于获取视频截图的后缀，0：秒，w：宽，h：高
                        $("#image").attr("src",resultData.domain+"/"+resultData.imgUrl+"?imageView2/2/w/400/h/400/q/100");
                    }
                };
                var putExtra = {
                    fname: "",                          //原文件名
                    params: {},                         //用来放置自定义变量
                    mimeType: null                      //限制上传文件类型
                };
                var config = {
                    region:qiniu.region.z2,             //存储区域(z0:代表华东;z2:代表华南,不写默认自动识别)
                    concurrentRequestLimit:3            //分片上传的并发请求量
                };
                var observable = qiniu.upload(file,resultData.imgUrl,resultData.token,putExtra,config);
                var subscription = observable.subscribe(observer);          // 上传开始
                // 取消上传
                // subscription.unsubscribe();
            }else{
                alert(resultData.message);                  //获取凭证失败
            }

            // if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
            //     layer.msg("删除成功！", {icon: 1});
            // }
        };
        AppComm.ajax.post('/file/ajax/qiniuUpToken', params, onSuccess);
    },
    qiniuDeleteByKey:function () {
        var qiniuDeleteKey = $.trim($("#qiniuDeleteKey").val());
        if (qiniuDeleteKey==null || qiniuDeleteKey=='') {
            layer.alert('key不能为空！',{
                icon: 5,
                kin: 'layer-ext-moon'
            });
            return false;
        }

        layer.load();
        var params = {
            key: qiniuDeleteKey
        };
        var onSuccess = function (resultData) {
            if (resultData.code==Enums.ResultEnum().SUCCESS.code) {
                layer.msg('删除成功',{icon: 1});
            } else {
                layer.msg("保存失败！", {icon: 2});
            }
            layer.closeAll('loading');
        };
        AppComm.ajax.post('/unit/ajax/qiniuDeleteByKey', params, onSuccess);
    }
};

qiniu_page.interface={
    init:function() {
        layui.use('code', function(){ //加载code模块
            layui.code({
                about: false
            }); //引用code方法
        });
    },
    uploadObjectInit: function () {
        var uploadObject = new FileUploadUnit("uploadObject");
        uploadObject.options.auto = false;
        // uploadObject.options.accepts = 'images';
        // uploadObject.options.acceptMime = 'image/*';
        // uploadObject.options.exts = 'jpg|png';

        uploadObject.callbackFun.choose = function(obj) {
            obj.preview(function(index, file, result){
                $('#fileName1').val(file.name);
                console.log(file.name);
            });
        };
        uploadObject.callbackFun.complete = function(res){
            var url = FileUploadUnit.getQiniuUrl(res);
            $("#image1").attr("src",url);
        };
        uploadObject.singleFileInit();


        var uploadObject2 = new FileUploadUnit("uploadObject2");
        uploadObject2.options.auto = false;
        uploadObject2.options.accepts = 'images';
        uploadObject2.options.acceptMime = 'image/*';
        uploadObject2.options.exts = 'jpg|png';
        uploadObject2.options.filePrefix = '2019/';

        uploadObject2.callbackFun.choose = function(obj) {
            $('#fileName2').val(obj.resultData.fileName);
            // obj.preview(function(index, file, result){
            //     $('#fileName2').val(file.name);
            //     console.log(file.name);
            // });
        };
        uploadObject2.callbackFun.complete = function(res){
            var url = FileUploadUnit.getQiniuUrl(res);
            $("#image2").attr("src",url);
        };
        uploadObject2.singleFileInit();


        var multipleUploadObject = new FileUploadUnit("multipleUploadObject");
        multipleUploadObject.options.field = "multipleFile";

        // multipleUploadObject.callbackFun.choose = function(obj) {
        // };
        multipleUploadObject.callbackFun.complete = function(res){
            console.log(res.key);
        };
        multipleUploadObject.multipleFileInit();

    }
};

qiniu_page.data={

};

AppComm.initFrame(qiniu_page);